package com.gzbugu.polytechsasia.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SQLExecuter {

	private static Logger log = LoggerFactory.getLogger(SQLExecuter.class);

	/**
	 * 查询
	 * 
	 * @param prepareSql
	 *            预备语句
	 * @param params
	 *            参数
	 * @return 返回Resultset instance
	 */
	@SuppressWarnings("unchecked")
	public static ResultSet find(String prepareSql, List<Object> params) {
		try {
			log.debug("find : " + prepareSql);
			Connection connection = DatabaseLinkDAO.getConnection();
			PreparedStatement preparedStatement = connection
					.prepareStatement(prepareSql);
			Iterator iter = params.iterator();
			for (int i = 1; iter.hasNext(); i++) {
				preparedStatement.setObject(i, iter.next());
			}
			log.debug("find successful");
			return preparedStatement.executeQuery();
		} catch (SQLException e) {
			log.error("find failed and return null", e);
			return null;
		}
	}

	/**
	 * 更新
	 * 
	 * @param prepareSql
	 *            预备语句
	 * @param params
	 *            参数
	 * @return 更新数目
	 */
	@SuppressWarnings("unchecked")
	public static int update(String prepareSql, List<Object> params) {
		log.debug("update : " + prepareSql);
		Connection connection = DatabaseLinkDAO.getConnection();
		try {
			PreparedStatement preparedStatement = connection
					.prepareStatement(prepareSql);
			Iterator iter = params.iterator();
			for (int i = 1; iter.hasNext(); i++) {
				preparedStatement.setObject(i, iter.next());
			}
			log.debug("update successful");
			int result = preparedStatement.executeUpdate();
			DatabaseLinkDAO.free(null, preparedStatement, connection);
			return result;
		} catch (SQLException e) {
			log.error("update failed and return 0", e);
			DatabaseLinkDAO.free(null, null, connection);
			return 0;
		}
	}

}
